package fwx.servlet;

import fwx.dao.UserDao;
import fwx.dao.impl.UserDaoImpl;
import fwx.model.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

@WebServlet(name = "LoginServlet", value = "/LoginServlet")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String userName = request.getParameter("username");
        String password = request.getParameter("password");
        User user = new User(userName, password);
        String save = request.getParameter("save");
        //从数据库查找是否存在这个用户
        UserDao userDao = new UserDaoImpl();
        //存储到session里
        HttpSession session = request.getSession();
        session.setAttribute("username", user.getName());
        //判断用户是否存在
        if (userDao.exist(user)) {
            //密码保存功能
            if ("save".equals(save)) {
                Cookie cookie = new Cookie("userName", userName);
                Cookie cookie1 = new Cookie("password", password);
                //密码保存1天
                cookie.setMaxAge(1 * 24 * 60 * 60);
                cookie1.setMaxAge(1 * 24 * 60 * 60);
            }
            //用户存在查询用户所有信息
            User user1 = userDao.findUser(user);
            //判断是不是管理员
            if (user1.getAdmin() == 1) {
                //跳转管理员页面
                request.getRequestDispatcher("index.jsp").forward(request,response);
            }
        }else {
            //用户不存在，刷新页面
            request.getRequestDispatcher("/login.html").forward(request,response);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
